package com.dbh.alg.algorithm.hot100.链表;

import com.dbh.alg.algorithm.hot100.ListNode;

/**
 * 给你一个单链表的头节点 head ，请你判断该链表是否为回文链表。如果是，返回 true ；否则，返回 false 。
 */
public class Leetcode234_回文链表 {

    public boolean isPalindrome(ListNode head) {
        ListNode mid = getMid(head);
        ListNode newHead = reverse(mid);
        while (newHead != null) {
            if (newHead.val != head.val) {
                return false;
            }
            newHead = newHead.next;
            head = head.next;
        }
        return true;
    }


    /**
     * 此处获取中间节点，链表不能截断，
     * @param head
     * @return
     */
    private ListNode getMid(ListNode head) {
//        ListNode pre = null;
        ListNode p1 = head;
        ListNode p2 = head;
        while (p2 != null && p2.next != null) {
//            pre = p1;
            p1 = p1.next;
            p2 = p2.next.next;
        }
//        pre.next = null;
        return p1;
    }

    private ListNode reverse(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        ListNode next = null;
        while (cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

    public static void main(String[] args) {
        ListNode p1 = new ListNode(1);
        ListNode p2 = new ListNode(2);
        ListNode p3 = new ListNode(3);
        ListNode p4 = new ListNode(4);

        p1.next = p2;
        p2.next = p3;
        p3.next = p4;
        Leetcode234_回文链表 leetcode234_回文链表 = new Leetcode234_回文链表();
        leetcode234_回文链表.isPalindrome(p1);
    }

}
